<template>
  <div class="datetime-picker">
    <van-popup v-model="show" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        :type="type"
        :title="title"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirm"
        @cancel="cancel"
      />
    </van-popup>
  </div>
</template>
<!--时间选择器-->
<script>
  export default {
    name: 'datetime-picker',

    props: {
      /**
       * 可选值为 date time year-month
       */
      type: {
        type: String,
        default: 'year-month'
      },
      value: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '选择时间'
      },
      minDate: {
        type: Date,
        default: new Date(2000, 1, 1)
      },
      maxDate: {
        type: Date,
        default: new Date()
      }
    },

    components: {},

    data () {
      return {
        show: this.value,
        currentDate: ''
      }
    },

    watch: {
      value (val) {
        this.show = val
      },
      show (val) {
        this.$emit('input', val)
      }
    },

    mounted () {
    },

    methods: {
      formatter (type, value) {
        if (type === 'year') {
          return `${value}年`;
        } else if (type === 'month') {
          return `${value}月`
        }
        return value;
      },

      confirm () {
        this.show = false
        this.$emit('confirm', this.timeFormat(this.currentDate))
      },

      timeFormat (time) {
        if (this.type === 'date' || this.type === 'year-month') {
          let year = time.getFullYear();
          let month = time.getMonth() + 1 >= 10 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1);
          let day = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate();
          return year + '年' + month + '月' + day + '日'
        } else {
          return time ? time : '00:00'
        }
      },
      cancel () {
        this.show = false
      }
    }
  }
</script>

<style lang="scss">
  .datetime-picker {
    .van-picker__cancel, .van-picker__confirm {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      line-height: 22px;
      color: #363D4E;
    }

    .van-picker__confirm {
      color: #4981EE;
    }

    .van-picker__title {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: bold;
      color: rgba(54, 61, 78, 1);
    }
  }
</style>
